/*
 * @(#)MouseDragger.java 1.0 10/12/13
 * 
 */
package interficie;

import java.awt.event.MouseEvent;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.SwingUtilities;
import javax.swing.event.MouseInputAdapter;

/**
 * Implementacion de una clase que crea un adaptador de mouse
 * para crear el efecto de drag & drop en un JList
 * 
 * @author Anna Lopez Mora
 *
 */
public class MouseDragger extends MouseInputAdapter {
    JList myList;
    DefaultListModel<String> myListModel;
	
    /**
     * Creadora de la clase 
     * 
     * @param list  		objeto de tipo lista que queremos adaptar
     * @param listmodel		modelo de lista con el contenido que esta debe tener
     */
    public MouseDragger(JList list, DefaultListModel<String> listmodel){
		myList = list;
		myListModel = listmodel;
	}
	
	private boolean mouseDragging = false;
    private int dragSourceIndex;

    
    /**
     * Las siguentes clases forman parte de la clase a la que
     * extiende esta, MouseInputAdapter
     */
    @Override
    public void mousePressed(MouseEvent e) {
        if (SwingUtilities.isLeftMouseButton(e)) {
            dragSourceIndex = myList.getSelectedIndex();
            mouseDragging = true;
        }
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        mouseDragging = false;
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        if (mouseDragging) {
            int currentIndex = myList.locationToIndex(e.getPoint());
            if (currentIndex != dragSourceIndex) {
                int dragTargetIndex = myList.getSelectedIndex();
                String dragElement = myListModel.get(dragSourceIndex);
                myListModel.remove(dragSourceIndex);
                myListModel.add(dragTargetIndex, dragElement);
                dragSourceIndex = currentIndex;
            }
        }
    }
}